from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from .models import Category, Image
from django.shortcuts import redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from .forms import RatingForm
from .models import Category, Image, Rating
from .forms import RatingForm
from myapp import models  # 确保你已经创建了 RatingForm
from django.contrib.auth.views import LoginView
from .forms import LoginForm
from django.views.generic import CreateView
from .forms import SignupForm


# myapp/views.py


# Create your views here.
def home(request):
    return HttpResponse("Hello, welcome to my website!")
def page1(request):
    # 使用render函数渲染myapp/界面1.html页面，并返回给用户
    return render(request, 'myapp/界面1.html')

def page2(request):
    # 获取查询参数 'service'
    service = request.GET.get('service', None)
    return render(request, 'myapp/界面2.html', {'service': service})

def page3(request):
    return render(request, 'myapp/界面3.html')

 # 显示所有分类和下拉列表

@login_required
def index(request):
    categories = Category.objects.all()  # 获取所有分类
    category_id = request.GET.get('category')  # 获取 URL 查询参数中的分类 ID
    
    if category_id:
        # 如果传入了分类 ID，则获取该分类对应的所有图片
        category = get_object_or_404(Category, pk=category_id)
        images = Image.objects.filter(category=category)
        return render(request, 'myapp/category_details.html', {'category': category, 'images': images})
    
    # 如果没有传入分类 ID，则渲染所有分类的列表
    return render(request, 'myapp/index.html', {'categories': categories})

#用户个人主页
def profile(request):
    return render(request, 'profile.html')

# 用户注册视图
def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')  # 注册成功后重定向到登录页面
    else:
        form = UserCreationForm()

    return render(request, 'myapp/signup.html', {'form': form})

# 定义登录视图函数
def login_view(request):
    # 判断请求方法是否为POST
    if request.method == 'POST':
        # 创建AuthenticationForm实例，并将POST请求的数据传入
        form = AuthenticationForm(request, data=request.POST)
        # 判断表单数据是否有效
        if form.is_valid():
            # 获取表单中的用户名和密码
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            # 使用authenticate函数验证用户名和密码是否正确
            user = authenticate(username=username, password=password)
            # 如果验证成功
            if user is not None:
                # 使用login函数登录用户
                login(request, user)
                return redirect('index')  # 登录成功后跳转到首页
    else:
        form = AuthenticationForm()
    return render(request, 'myapp/login.html', {'form': form})

# 用户注销视图
def logout_view(request):
    logout(request)
    return redirect('myapp/registration/logout.html')  # 注销后跳转到登录页
from django.db.models import Avg
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .forms import RatingForm
from .models import Category, Image, Rating

@login_required
def category_details(request, category_id):
    category = get_object_or_404(Category, pk=category_id)
    # 获取所有属于该分类的图片并注入平均评分
    images = Image.objects.filter(category=category).annotate(
        total_rating=Avg('ratings__rating_id')  # 计算每张图片的平均评分
    )

    for image in images:
        # 获取当前用户的评分
        user_rating = image.ratings.filter(user=request.user).first()
        image.user_rating = user_rating.rating_id if user_rating else None  # 当前用户的评分

        # 获取所有用户评分详情
        image.all_user_ratings = ", ".join([f"{rating.user.username}: {rating.rating_id}" for rating in image.ratings.all()]) if image.ratings.exists() else '暂无评分'

    # 处理表单提交
    if request.method == 'POST':
        image_id = request.POST.get('image_id')
        image = get_object_or_404(Image, pk=image_id)

        # 检查用户是否已经评分
        existing_rating = Rating.objects.filter(image=image, user=request.user).first()
        if existing_rating:
            form = RatingForm(request.POST, instance=existing_rating)
        else:
            form = RatingForm(request.POST)
            form.instance.image = image
            form.instance.user = request.user

        if form.is_valid():
            form.save()  # 保存评分
            return redirect('category_details', category_id=category.id)  # 刷新页面

    # 创建 form_dict 用于渲染每张图片的评分表单
    form_dict = {}
    for image in images:
        form_dict[image.id] = RatingForm()

    return render(request, 'myapp/category_details.html', {
        'category': category,
        'images': images,
        'form_dict': form_dict,
    })

class CustomLoginView(LoginView):
    authentication_form = LoginForm
    template_name = 'myapp/界面1.html'

class SignupView(CreateView):
    form_class = SignupForm
    template_name = 'myapp/界面1.html'
    success_url = '/'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['signup_form'] = context['form']
        return context
